package org.example;

/**
 * @Version: 1.0
 * @ClassName: Test13_Java
 * @Author: Vesper-Z
 * @Date: 2024-04-03 21:17
 * @Description: 代理模式和委托模式
 **/
public class Test13_Java {
    public static void main(String[] args) {
        ComputerProxy computerProxy = new ComputerProxy("塞尔达之王国之类");
        computerProxy.openComputer();
        computerProxy.playGame();
        computerProxy.playGame();

        ChefImpl chef = new ChefImpl("水饺");
        DelegateChef delegateChef = new DelegateChef(chef);
        delegateChef.cook();
    }
}

//代理接口
interface Computer {
    void playGame();
}

//被代理类
class RealComputerProxy implements Computer {
    private String game_name;

    public RealComputerProxy(String game_name) {
        this.game_name = game_name;
    }

    @Override
    public void playGame() {
        System.out.println("play game of " + game_name);
    }

    public void openComputer() {
        System.out.println("computer is opened!");
    }
}
//代理类
class ComputerProxy implements Computer {
    private String game_name;
    private RealComputerProxy realComputerProxy;

    public ComputerProxy(String game_name) {
        this.game_name = game_name;
    }

    @Override
    public void playGame() {
        if (realComputerProxy == null) {
            System.out.println("Error: computer is not open!");
        } else {
            this.realComputerProxy.playGame();
        }
    }

    public void openComputer() {
        if (realComputerProxy == null) {
            System.out.println("computer is opening now!");
            realComputerProxy = new RealComputerProxy(this.game_name);
        }
        this.realComputerProxy.openComputer();

    }
}

/**
 * 委托模式
 */
//委托接口
interface Chef{
    void cook();
}

//被委托类实现类
class ChefImpl implements Chef{
    private String name;

    public ChefImpl(String name) {
        this.name = name;
    }
    @Override
    public void cook() {
        System.out.println("厨师在做饭，做的是"+name);
    }

}

//代理类
class  DelegateChef implements Chef{
    private Chef mChef;

    public DelegateChef(Chef chef) {
        this.mChef = chef;
    }

    @Override
    public void cook() {
        mChef.cook();
    }
}



